﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.IO.Extensions;
using Abp.UI;
using KelonProud.Administration.Managers.Authorization;
using KelonProud.Domain.Dtos;
using KelonProud.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace KelonProud.Administration.Controllers
{
    [Route("Admin/[controller]/[action]")]
    public class AttachmentController : KelonProudControllerBase
    {
        private readonly Object thisLock = new object();
        private readonly AttachmentManager _attachmentManager;
        private readonly IHostingEnvironment _hostingEnvironment;


        public AttachmentController(
            IHostingEnvironment hostingEnvironment, 
            AttachmentManager attachmentManager)
        {
            _hostingEnvironment = hostingEnvironment;
            _attachmentManager = attachmentManager;
        }

        [AbpMvcAuthorize]
        //查看图片
        public ActionResult CheckImg(string attachmentIds)
        {
            var model = attachmentIds.HasValue()
                ? attachmentIds.Split(',').Select(s =>
                {
                    var accessory = _attachmentManager.GetById(s.ToInt32());
                    if (accessory != null)
                        return Url.Action("GetAttachment", "Attachment", new { id = accessory.Id });
                    else
                        return null;
                }).Where(w => w != null).ToList()
                : new List<string>();

            return View("HonkSoft.Admin.Views.Attachment.CheckImg", model);
        }

        [AbpMvcAuthorize]
        public ActionResult Upload(string fileUploadPath = "/uploadFiles/Temp/", string displayName = "")
        {
            var loclDirectory = _hostingEnvironment.WebRootPath + fileUploadPath;

            if (Request.Form.Files.Count == 0)
            {
                throw new UserFriendlyException("上传文件为空");
            }
            var file = Request.Form.Files[0];
            var name = displayName == "" ? Path.GetFileName(file.FileName) : displayName;
            var resultId = -1;

            if (!Directory.Exists(loclDirectory))
            {
                Directory.CreateDirectory(loclDirectory);
            }
            var attachment = _attachmentManager.SaveOnFileFolder(name, file.ContentType, fileUploadPath,
                (int) file.OpenReadStream().Length / 1024);
            var fileFullPath = loclDirectory + attachment.FileName + attachment.FileExtension;


            using (var fs = System.IO.File.Create(fileFullPath))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            resultId = attachment.Id;

            return Json(data: new {attachmentId = resultId, fileFullPath = attachment.ImageVirtualPath});
        }

        [AbpMvcAuthorize]
        public ActionResult Remove(int attachmentId)
        {
            _attachmentManager.Delete(attachmentId);

            return Json("删除成功");
        }

        public FileResult GetAttachment(int id)
        {
            var attachment = _attachmentManager.GetById(id);

            var loclPath = _hostingEnvironment.WebRootPath + attachment.FileFolderPath;
            //var loclPath = HttpContext.Server.MapPath(accessory.FileFolderPath);
            var path = string.Concat(loclPath, attachment.FileName + attachment.FileExtension);

            if (System.IO.File.Exists(path))
            {
                var fs = new FileStream(path, FileMode.Open);
                return File(fs, attachment.ContentType, attachment.DisplayName);
            }
            else
            {
                lock (thisLock)
                {
                    path = _hostingEnvironment.WebRootPath + "/images/picture_error.png";
                    var fs = new FileStream(path, FileMode.Open);
                    var ms = new MemoryStream(fs.GetAllBytes());
                    fs.Close();
                    fs.Dispose();

                    return File(ms, attachment.ContentType, attachment.DisplayName);
                }
            }
        }

        public ActionResult GetAttachmentUrl(int id)
        {
            var attachment = _attachmentManager.GetById(id);
            var result = "";

            var loclPath = _hostingEnvironment.WebRootPath + attachment.FileFolderPath;
            //var loclPath = HttpContext.Server.MapPath(accessory.FileFolderPath);
            var path = string.Concat(loclPath, attachment.FileName + attachment.FileExtension);

            if (System.IO.File.Exists(path))
            {
                result = path;
            }
            else
            {
                lock (thisLock)
                {
                    result = _hostingEnvironment.WebRootPath + "/images/picture_error.png";
                }
            }

            return Json(new {filePath = result});
        }
    }
}
